package com.weiaibenpao.demo.chislim.sport;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.Interface.OnSportRecordListener;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.adater.RecyclerSportSelectAdapter;
import com.weiaibenpao.demo.chislim.bean.AddSportsBean;
import com.weiaibenpao.demo.chislim.bean.BluResult;
import com.weiaibenpao.demo.chislim.bean.UserBean;
import com.weiaibenpao.demo.chislim.ble.adapter.DeviceAdapter;
import com.weiaibenpao.demo.chislim.ble.entity.EntityDevice;
import com.weiaibenpao.demo.chislim.ble.service.BLEService;
import com.weiaibenpao.demo.chislim.ble.utils.BluetoothController;
import com.weiaibenpao.demo.chislim.ble.utils.ConstantUtils;
import com.weiaibenpao.demo.chislim.ble.utils.Util;
import com.weiaibenpao.demo.chislim.ui.MusicTypeActivity;
import com.weiaibenpao.demo.chislim.util.BluDataUtil;
import com.weiaibenpao.demo.chislim.util.Default;
import com.weiaibenpao.demo.chislim.util.GetIntentData;
import com.weiaibenpao.demo.chislim.util.LatLong_impl;
import com.weiaibenpao.demo.chislim.util.SportAlertDialogUtil;
import com.weiaibenpao.demo.chislim.util.VoicePlayerUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.View.VISIBLE;
import static com.weiaibenpao.demo.chislim.R.id.stateText;
import static com.weiaibenpao.demo.chislim.sport.FavouritePicActivity.latLongList;

public class FavouritMapActivity extends AppCompatActivity {

    BluetoothAdapter mAdapter;             //蓝牙适配器
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.myTop)
    RelativeLayout myTop;
    @BindView(R.id.stateImg)
    ImageView stateImg;
    @BindView(R.id.heart)
    TextView heart;
    @BindView(R.id.cor)
    TextView cor;
    @BindView(R.id.dis)
    TextView dis;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.mySpeedAdd)
    ImageView mySpeedAdd;
    @BindView(R.id.speedText)
    TextView speedText;
    @BindView(R.id.mySpeedMinu)
    ImageView mySpeedMinu;
    @BindView(R.id.speedLayout)
    LinearLayout speedLayout;
    @BindView(R.id.mySlopeAdd)
    ImageView mySlopeAdd;
    @BindView(R.id.slopeText)
    TextView slopeText;
    @BindView(R.id.mySlopeMinu)
    ImageView mySlopeMinu;
    @BindView(R.id.slopeLayout)
    LinearLayout slopeLayout;
    @BindView(R.id.root_rv)
    ImageView rootRv;
    @BindView(R.id.addFastSpeed)
    ImageView addFastSpeed;
    @BindView(R.id.lowFastSpeed)
    ImageView lowFastSpeed;
    @BindView(R.id.activity_my_view)
    RelativeLayout activityMyView;

    //加载图形的图层
    @BindView(R.id.rootView)
    RelativeLayout rootView;
    @BindView(R.id.startStopState_Text)
    TextView startStopStateText;
    @BindView(R.id.maplocationLayout)
    LinearLayout maplocationLayout;
    @BindView(R.id.kuaijie)
    RelativeLayout kuaijie;
    @BindView(R.id.jieshu)
    RelativeLayout jieshu;

    private PopupWindow mPopupWindow;
    private ListView listView;
    private static final String TAG = "蓝牙";
    private ArrayList bluList;
    private ArrayList<EntityDevice> list = new ArrayList<EntityDevice>();
    Intent intentService;
    DeviceAdapter deviceAdapter;

    private MsgReceiver receiver;
    BluetoothController controller = BluetoothController.getInstance();
    BluResult bluResult;
    Util u = new Util();
    BluDataUtil bluDataUtil = new BluDataUtil();
    Context context;

    public int bluState = 0;
    public double sportDis = 0;   //运动里程
    public String sportTime;   //运动时间
    public int sportCor;    //消耗卡路里
    public float minSpeed;    //最小速度
    public float maxSpeed;      //最大速度
    public int maxSlope;     //最大坡度

    private VoicePlayerUtil voicePlayerUtil;

    MapView mapView = null;
    AMap aMap;

    LatLong_impl latLong_impl;   //用来获取系统日期
    DecimalFormat decimalFormat;

    WindowManager wm;
    int widthScreen;
    int heightScreen;
    private SharedPreferences mSharedPreferences;
    Intent myIntent;
    int disPlan;// 计划跑步距离

    private PopupWindow mPopupSpeed;

    double cenLat;
    double cenLong;
    float zoom;

    String imageUrl;
    String imageUrlline;

    RecyclerView fastSelect;
    ArrayList arraySpeedList;
    RecyclerSportSelectAdapter adapterSpeed;

    LatLng latLng1;
    LatLng latLng2;
    /**
     * 绘制跑步轨迹
     */
    GetIntentData getIntentData;

    StringBuilder locusphoto = new StringBuilder("");    //轨迹
    SportAlertDialogUtil sportAlertDialogUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favourit_map);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this , getResources().getColor(R.color.ku_bg ) , 0);
        //获取地图控件的引用
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);                                   // 此方法必须重写

        ButterKnife.bind(this);
        context = getApplicationContext();
        getIntentData = new GetIntentData();
        initReceiver2();                                                          //蓝牙模块状态
        initService();
        initData();
        registerReceiver();
        MyConTrol(0);

//        voicePlayerUtil = new VoicePlayerUtil(this);

        sportAlertDialogUtil = new SportAlertDialogUtil();

        latLong_impl = new LatLong_impl(context);

        decimalFormat = new DecimalFormat("0.0");//构造方法的字符格式这里如果小数不足2位,会以0补足.

        initMap();

        myIntent = getIntent();
        disPlan = myIntent.getIntExtra("dis", 1000);                 //
        cenLat = myIntent.getDoubleExtra("cenLat", 39.90866);       //获取地图中心点
        cenLong = myIntent.getDoubleExtra("cenLong", 116.397486);   //获取地图中心点
        zoom = myIntent.getFloatExtra("zoom", 15);
        setIntro(cenLat, cenLong, zoom);                             //设置地图中心点

        arraySpeedList = new ArrayList();
        for (int i = 3; i < 15; i++) {
            arraySpeedList.add(i + "km/h");
        }
        adapterSpeed = new RecyclerSportSelectAdapter(context, arraySpeedList);

        initStartSportMark();

        initAction();

        getTotalNum();

        setMarkerRun();
    }

    @OnClick({R.id.back, R.id.mySpeedAdd, R.id.mySpeedMinu, R.id.mySlopeAdd, R.id.mySlopeMinu, R.id.root_rv, R.id.addFastSpeed, R.id.lowFastSpeed, stateText})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.stateText:
                Intent intent = new Intent(this , MusicTypeActivity.class);
                startActivity(intent);
                break;
            case R.id.root_rv:
                if (mAdapter == null) {
                    mAdapter = BluetoothAdapter.getDefaultAdapter();
                }
                if (!mAdapter.isEnabled()) {                                  //判断蓝牙是否打开
                    initReceiver2();
                    //弹出对话框提示用户是后打开
                    Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enabler, Default.FIND);
                    //不做提示，强行打开
                    // mAdapter.enable();
                }

                if (mAdapter.isEnabled() && bluState == 0) {                //判断蓝牙是否连接
                    list.clear();//清空以前发现的蓝牙
                    deviceAdapter.notifyDataSetChanged();
                    if (!BluetoothController.getInstance().initBLE()) {///手机不支持蓝牙
                        Toast.makeText(FavouritMapActivity.this, "您的手机不支持蓝牙",
                                Toast.LENGTH_SHORT).show();
                        return;//手机不支持蓝牙就啥也不用干了，关电脑睡觉去吧
                    }
                    new GetDataTask().execute();// 搜索任务

                    //-------------------------------------------------------------------------
                    //Log.i("蓝牙",device.toString());
                }
                if (bluState == 10) {               //正在运转
                    controller.write(bluDataUtil.startStop("1"));     //启动

                } else if (bluState == 20) {       //正在停止


                    //提交数据
                    isDis();
                }
                break;
            case R.id.mySpeedAdd:
                Log.i(TAG, "速度增加");
                float speed1 = Float.parseFloat(speedText.getText().toString());
                Log.i(TAG, "速度增加" + speed1 + "---" + maxSpeed);
                if (speed1 < maxSpeed) {
                    speed1 = speed1 + (float) 0.1;
                } else {
                    speed1 = maxSpeed;
                }
                Log.i(TAG, "速度增加" + speed1 + "---" + maxSpeed);
                controller.write(bluDataUtil.addSpeed(decimalFormat.format(speed1)));
                break;
            case R.id.mySpeedMinu:
                Log.i(TAG, "速度减少");
                float speed2 = Float.parseFloat(speedText.getText().toString());
                if (speed2 > minSpeed) {
                    speed2 = speed2 - (float) 0.1;
                } else {
                    speed2 = minSpeed;
                }
                controller.write(bluDataUtil.addSpeed(decimalFormat.format(speed2)));
                break;
            case R.id.mySlopeAdd:
                Log.i(TAG, "坡度增加");
                int slope1 = Integer.parseInt(slopeText.getText().toString());
                if (slope1 < maxSlope) {
                    slope1 = slope1 + 1;
                } else {
                    slope1 = maxSlope;
                }
                controller.write(bluDataUtil.addSlope(slope1 + "")); //坡度增加
                break;
            case R.id.mySlopeMinu:
                Log.i(TAG, "坡度减少");
                int slope2 = Integer.parseInt(slopeText.getText().toString());
                if (slope2 > 1) {
                    slope2 = slope2 - 1;
                } else {
                    slope2 = 0;
                }
                controller.write(bluDataUtil.addSlope(slope2 + ""));   //坡度减少
                break;
            case R.id.back:
                finish();
                break;
            case R.id.addFastSpeed:
                controller.write(bluDataUtil.addSpeed(String.valueOf(0.6)));
                break;
            case R.id.lowFastSpeed:
                showSpeedPopwindow(getWindow().getDecorView());
                break;
        }
    }

    public void initAction(){
        getIntentData.setOnSportRecordListener(new OnSportRecordListener() {
            @Override
            public void onUploadSuccess(Object object) {
                Log.i("失败","成功成功成功成功成功");
                AddSportsBean.DataBean dataBean = (AddSportsBean.DataBean) object;

                Intent intent = new Intent(FavouritMapActivity.this,SportRecordShareActivity.class);
                intent.putExtra(Default.SPORT_HISTORY_URL,dataBean.getUrl());

                startActivity(intent);
                doFinish();
            }

            @Override
            public void onUploadFailed(String str) {
                Log.i("失败","失败失败失败失败");
            }
        });


        sportAlertDialogUtil.setOnListener(new SportAlertDialogUtil.OnListen() {
            @Override
            public void cancle() {

            }

            @Override
            public void okCommit() {
                if(locusphoto.length() > 0){
                    locusphoto =  locusphoto.deleteCharAt(locusphoto.length()-1);
                }
                updateData();
            }

            @Override
            public void abandon() {
                doFinish();
            }
        });
    }

    /**
     * 地图的显示与隐藏
     */
    boolean flagMaplocationLayout = false;

    @OnClick(R.id.maplocationLayout)
    public void onClick() {
        if (!flagMaplocationLayout) {
            rootView.setVisibility(VISIBLE);
            flagMaplocationLayout = true;
        } else {
            rootView.setVisibility(View.GONE);
            flagMaplocationLayout = false;
        }
    }

    public void initMap() {
        aMap = mapView.getMap();

        aMap.setTrafficEnabled(true);// 显示实时交通状况
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 地图模式

        wm = this.getWindowManager();

        widthScreen = wm.getDefaultDisplay().getWidth();
        heightScreen = wm.getDefaultDisplay().getHeight();
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

            }
        });
        huizhi();
    }

    /**
     * 绘制预设轨迹
     */
    PolylineOptions polylineOptionsY;
    public void huizhi() {
        for(int i = 0;i < latLongList.size() ;i++){
            polylineOptionsY = latLongList.get(i);

            polylineOptionsY.visible(true).width(15).zIndex(200);
            polylineOptionsY.color(Color.argb(255, 24, 159, 246));
            //加入对应的颜色,使用colorValues 即表示使用多颜色，使用color表示使用单色线
            //polylineOptions.colorValues(WalkUtil.getColorList(latLongList.size() / 144 + 1, this));
            //加上这个属性，表示使用渐变线
            polylineOptionsY.useGradient(true);
            aMap.addPolyline(polylineOptionsY);
        }
    }

    /**
     * 总点数
     * @return
     */
    int numTotal=0;
    ArrayList arrayListNum;
    private int getTotalNum(){
        arrayListNum = new ArrayList();
        for(int i = 0;i < latLongList.size() ;i++){
            arrayListNum.add(latLongList.get(i).getPoints().size());
            numTotal += latLongList.get(i).getPoints().size();
            for(int j = 0;j<latLongList.get(i).getPoints().size();j++){
                locusphoto =locusphoto.append(latLongList.get(i).getPoints().get(j).longitude + "," + latLongList.get(i).getPoints().get(j).latitude + ":");   //轨迹
            }

            if(locusphoto.length() > 0){
                locusphoto =  locusphoto.deleteCharAt(locusphoto.length()-1);
                locusphoto.append(";");
            }

        }
        return numTotal;
    }
    int n = 0;
    private void getNowNum(int dis,int disPlan){

        if(dis >= disPlan){
            n = numTotal;
        }else{
            n = (int) (((float) dis/disPlan) * numTotal);
        }

        Log.i("点数","----------当前点数： " + n + "----------总点数： " + numTotal);
        //huizhiSports(n);
        huizhiSports(n);

    }

    //当前连线的点数
    PolylineOptions op1;
    int a=0;
    int p=0;
    /**
     * @param num  每次画点的数
     */
    PolylineOptions polylineOptions;
    LatLng latLngRun ;
    Polyline polyline;
    public void huizhiSports(int n) {
        if(polyline != null){
        //    polyline.remove();
            polyline = null;
        }
        if(n >= numTotal){
            n = numTotal;
        }
        for(int i = 0;i < latLongList.size() ;i++){
                polylineOptions = new PolylineOptions();
            polylineOptions.visible(true).width(15).zIndex(200);
            polylineOptions.color(Color.argb(255, 204, 53, 143));
            if(n > (int)arrayListNum.get(i)){
                p = (int) arrayListNum.get(i);
                n = n - p;
                for(int j = 0;j<p;j++){
                    polylineOptions.add(latLongList.get(i).getPoints().get(j));
                    latLngRun = latLongList.get(i).getPoints().get(j);
                }
                //locationImg(latLngRun);
                polyline = aMap.addPolyline(polylineOptions);
            }else {
                for(int j = 0;j<n;j++){
                    polylineOptions.add(latLongList.get(i).getPoints().get(j));
                    latLngRun = latLongList.get(i).getPoints().get(j);
                }
                //locationImg(latLngRun);
                polyline = aMap.addPolyline(polylineOptions);
                break;
            }
        }
    }

    /**
     * 当前位置标记
     */
    public void locationImg(LatLng latLng){
        if(marker != null){
            marker.remove();
        }
        markerRun.position(latLng);
        marker = aMap.addMarker(markerRun);
    }

    //设置帧动画
    ArrayList iconList;
    MarkerOptions markerRun = new MarkerOptions();
    Marker marker;
    public void setMarkerRun(){

        iconList = new ArrayList();
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_1)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_2)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_3)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_4)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_5)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_6)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_7)));
        iconList.add(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.run_8)));

        markerRun.draggable(false);   //设置Marker可拖动
        markerRun.icons(iconList);
        markerRun.period(5);        //值越小刷新的越快
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerRun.setFlat(true);//设置marker平贴地图效果

    }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    //注册广播，用于监听蓝牙状态
    public void initReceiver2() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(bluetoothState, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(bluetoothState, filter);
    }

    //接收蓝牙模块状态广播
    BroadcastReceiver bluetoothState = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String stateExtra = BluetoothAdapter.EXTRA_STATE;
            int state = intent.getIntExtra(stateExtra, -1);
            switch (state) {
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.i("蓝牙", "蓝牙模块正在打开");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.i("蓝牙", "蓝牙已打开");

                    list.clear();//清空以前发现的蓝牙
                    deviceAdapter.notifyDataSetChanged();
                    if (!BluetoothController.getInstance().initBLE()) {///手机不支持蓝牙
                        Toast.makeText(FavouritMapActivity.this, "您的手机不支持蓝牙",
                                Toast.LENGTH_SHORT).show();
                        return;//手机不支持蓝牙就啥也不用干了，关电脑睡觉去吧
                    }
                    new GetDataTask().execute();// 搜索任务

                    //-------------------------------------------------------------------------
                    //Log.i("蓝牙",device.toString());
                    MyConTrol(1);
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.i("蓝牙", "蓝牙模块正在关闭");
                    break;
                case BluetoothAdapter.STATE_OFF:
                    Log.i("蓝牙", "蓝牙模块处于关闭状态");
                    break;
            }
        }
    };

    /**
     * 0--9 有坡度的跑步机
     * 10--19  没坡度的跑步机
     * @param stateNum
     */
    public void MyConTrol(int stateNum) {
        switch (stateNum) {
            case 0:                                           //蓝牙未开启状态
                speedLayout.setVisibility(View.INVISIBLE);
                slopeLayout.setVisibility(View.INVISIBLE);
                //    stateImg.setBackgroundColor(getResources().getColor(R.color.red_yuan));
                break;
            case 1:                                           //蓝牙未连接状态
                speedLayout.setVisibility(View.INVISIBLE);
                slopeLayout.setVisibility(View.INVISIBLE);
                //    stateImg.setBackgroundColor(getResources().getColor(R.color.yellow_bg));
                break;
            case 2:                                           //蓝牙连接成功状态
                speedLayout.setVisibility(VISIBLE);
                slopeLayout.setVisibility(VISIBLE);
                //    stateImg.setBackgroundColor(getResources().getColor(R.color.green_yuan));
                break;
            case 3:
                break;
            case 4:
                break;
            case 10:
                speedLayout.setVisibility(View.INVISIBLE);
                slopeLayout.setVisibility(View.INVISIBLE);
                break;
            case 11:
                break;
            case 12:
                break;
            case 13:
                break;
            case 14:
                Log.i("蓝牙", "连接成功！");
                break;
        }
    }

    /**
     * 更新界面
     */
    int disTab;
    public void changeActivity(BluResult bluResult) {
        speedText.setText(bluResult.speed + "");
        slopeText.setText(bluResult.slope + "");
        time.setText(bluResult.time.replace (".", ":"));
        cor.setText(bluResult.calories + "");
        heart.setText(bluResult.heart + "");
        dis.setText(bluResult.distance + "");

        if ((int) (Double.parseDouble(bluResult.distance) * 1000) != disTab) {
    //      huizhiSports((int)(Float.parseFloat(bluResult.distance)*1000), disPlan);
            getNowNum((int)(Float.parseFloat(bluResult.distance)*1000), disPlan);
            disTab = (int) (Double.parseDouble(bluResult.distance) * 1000);
        }

        MyConTrol(2);
        if (bluState == 20) { //跑步机正在运转
            startStopStateText.setText("停止");
            speedLayout.setVisibility(View.VISIBLE);
            slopeLayout.setVisibility(View.VISIBLE);
            addFastSpeed.setVisibility(View.VISIBLE);
            lowFastSpeed.setVisibility(View.VISIBLE);
            kuaijie.setVisibility(View.VISIBLE);
            jieshu.setVisibility(View.VISIBLE);
        }

        if (bluState == 30) {   //跑步机正在加速
            startStopStateText.setText("正在加速");
            speedLayout.setVisibility(View.VISIBLE);
            slopeLayout.setVisibility(View.VISIBLE);
            addFastSpeed.setVisibility(View.VISIBLE);
            lowFastSpeed.setVisibility(View.VISIBLE);
            kuaijie.setVisibility(View.VISIBLE);
            jieshu.setVisibility(View.VISIBLE);
        }

        if (bluState == 40) {   //跑步机正在减速
            startStopStateText.setText("正在减速");
            speedLayout.setVisibility(View.VISIBLE);
            slopeLayout.setVisibility(View.VISIBLE);
            addFastSpeed.setVisibility(View.VISIBLE);
            lowFastSpeed.setVisibility(View.VISIBLE);
            kuaijie.setVisibility(View.VISIBLE);
            jieshu.setVisibility(View.VISIBLE);
        }

        if (bluState == 10) {  //跑步处于停止状态
            startStopStateText.setText("开始");
            speedLayout.setVisibility(View.VISIBLE);
            slopeLayout.setVisibility(View.VISIBLE);
            addFastSpeed.setVisibility(View.VISIBLE);
            lowFastSpeed.setVisibility(View.VISIBLE);
            kuaijie.setVisibility(View.VISIBLE);
            jieshu.setVisibility(View.VISIBLE);
        }

        if (bluState == 60) {      //安全锁脱落
            speedLayout.setVisibility(View.GONE);
            slopeLayout.setVisibility(View.GONE);
            addFastSpeed.setVisibility(View.GONE);
            lowFastSpeed.setVisibility(View.GONE);
            kuaijie.setVisibility(View.GONE);
            jieshu.setVisibility(View.GONE);
            startStopStateText.setText("安全锁脱落");
        }
    }

    /**
     * 显示蓝牙搜索结果
     * @param parent
     */
    private void showPopwindow(View parent, final ArrayList bluList) {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        if (mPopupWindow == null) {
            LayoutInflater mLayoutInflater = LayoutInflater.from(this);
            View contentView = mLayoutInflater.inflate(R.layout.group_list, null);
            listView = (ListView) contentView.findViewById(R.id.lv_group);

            deviceAdapter = new DeviceAdapter(this, bluList);
            listView.setAdapter(deviceAdapter);

            mPopupWindow = new PopupWindow(contentView, screenWidth / 1, screenHeight / 3);
        }
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);  //设置点击屏幕其它地方弹出框消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());

        // 显示的位置为:屏幕的宽度的1/16
        // mPopupWindow.showAsDropDown(parent, screenWidth / 1, screenHeight/2);
        mPopupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //蓝牙设备选择连接，点击列表中的蓝牙名称，连接对应设备
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                if (BluetoothController.reBtGatt() == null) {
                    //连接设备
                    BluetoothController.getInstance().connect((EntityDevice) bluList.get(position));
                } else {
                    BluetoothController.clearBtGatt();
                    BluetoothController.getInstance().connect((EntityDevice) bluList.get(position));
                }
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            }
        });
    }

    private void initData() {
        bluList = new ArrayList();
        deviceAdapter = new DeviceAdapter(this, list);
    }

    /**
     * 实例化服务
     */
    private void initService() {
        //开始服务
        intentService = new Intent(FavouritMapActivity.this, BLEService.class);
        startService(intentService);
        //初始化蓝牙
        BluetoothController.getInstance().initBLE();
    }

    /**
     * 注册广播
     */
    private void registerReceiver() {
        receiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstantUtils.ACTION_UPDATE_DEVICE_LIST);
        intentFilter.addAction(ConstantUtils.ACTION_CONNECTED_ONE_DEVICE);
        intentFilter.addAction(ConstantUtils.ACTION_RECEIVE_MESSAGE_FROM_DEVICE);
        intentFilter.addAction(ConstantUtils.ACTION_STOP_CONNECT);
        registerReceiver(receiver, intentFilter);
    }


    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            if (BluetoothController.getInstance().isBleOpen()) {
                BluetoothController.getInstance().startScanBLE();
            }
            ;// 开始扫描
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            super.onPostExecute(result);
        }
    }

    /**
     * 接收广播，接收蓝牙模块发过来的值
     */
    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(
                    ConstantUtils.ACTION_UPDATE_DEVICE_LIST)) {
                String name = intent.getStringExtra("name");
                String address = intent.getStringExtra("address");
                boolean found = false;                                            //记录该条记录是否已在list中，
                for (EntityDevice device : list) {
                    if (device.getAddress().equals(address)) {
                        found = true;
                        break;
                    }
                }// for
                if (!found) {                                                       //发现蓝牙
                    EntityDevice temp = new EntityDevice();
                    temp.setName(name);
                    temp.setAddress(address);
                    list.add(temp);
                    showPopwindow(getWindow().getDecorView(), list);              //显示蓝牙列表
                    deviceAdapter.notifyDataSetChanged();
                }
            } else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_CONNECTED_ONE_DEVICE)) {
                // connectedDevice.setText("连接的蓝牙是："+intent.getStringExtra("address"));
            } else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_STOP_CONNECT)) {
                // connectedDevice.setText("");
                toast("连接已断开");
            } else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_RECEIVE_MESSAGE_FROM_DEVICE)) {
                //receivedMessage.append(u.toStringHex(intent.getStringExtra("message")).trim());
                //Log.i("蓝牙数据",u.toStringHex(intent.getStringExtra("message")).trim());
                bluResult = bluDataUtil.SplitStr(u.toStringHex(intent.getStringExtra("message")).trim(), context);
                if (bluResult != null) {
                    if (bluResult.code.equals("0")) {
                        bluState = Integer.parseInt(bluResult.state);
                        sportDis = Double.parseDouble(bluResult.distance);
                        sportCor = Integer.parseInt(bluResult.calories);
                        maxSpeed = (int) (Double.parseDouble(bluResult.maxSpeed));           //最大速度
                        maxSlope = Integer.parseInt(bluResult.maxSlope);                     //最大坡度
                        minSpeed = Float.parseFloat(bluResult.minSpeed);                     //最小速度
                        sportTime = bluResult.time;
                        changeActivity(bluResult);
                    }
                }
            }
        }
    }

    private void toast(String str) {
        Toast.makeText(FavouritMapActivity.this, str, Toast.LENGTH_SHORT).show();
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 销毁
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();

        stopService(intentService);
        unregisterReceiver(receiver);
        unregisterReceiver(bluetoothState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mapView.onResume();
        SportAlertDialogUtil.showAppIsQMSDialog(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 显示快捷操作结果
     *
     * @param parent
     */
    private void showSpeedPopwindow(View parent) {

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        if (mPopupSpeed == null) {
            LayoutInflater mLayoutInflater = LayoutInflater.from(this);
            View contentView = mLayoutInflater.inflate(R.layout.pop_blucontrol, null);

            fastSelect = (RecyclerView) contentView.findViewById(R.id.fastSelect);
            fastSelect.setLayoutManager(new LinearLayoutManager(this,
                    LinearLayoutManager.VERTICAL, false));

            fastSelect.setAdapter(adapterSpeed);
            adapterSpeed.setOnItemClickListener(new RecyclerSportSelectAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    controller.write(bluDataUtil.addSpeed(String.valueOf(position + 3)));
                    mPopupSpeed.dismiss();
                }
            });

            mPopupSpeed = new PopupWindow(contentView, screenWidth / 1, screenHeight / 3);
        }
        mPopupSpeed.setFocusable(true);
        mPopupSpeed.setOutsideTouchable(true);                                                   //设置点击屏幕其它地方弹出框消失
        mPopupSpeed.setBackgroundDrawable(new BitmapDrawable());

        // 显示的位置为:屏幕的宽度的1/16
        // mPopupSpeed.showAsDropDown(parent, screenWidth / 1, screenHeight/2);
        mPopupSpeed.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 切换地图显示中心点
     */
    public void setIntro(double latNow, double longNow, float n) {
        LatLng marker1 = new LatLng(latNow, longNow);
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(n));
    }

    /**
     * 绘制起点和终点
     * int startX;    //起点
     * int startY;
     * int stopX;    //终点
     * int stopY;
     */
    public void initStartSportMark() {

        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng1);
        markerOption.draggable(false);   //设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.staring_point)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);

        markerOption.position(latLng2);
        markerOption.draggable(false);   //设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(), R.drawable.end_point)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果
        aMap.addMarker(markerOption);
    }

    public long getDate(String str){
        double dou = Double.parseDouble(str);

        int h = (int) (dou / 1);

        int s = (int) (dou * 100)%100;

        return h*60 + s;
    }

    /**
     * 判断是否大于100米
     */
    public void isDis(){
        if(sportDis > 0.1){
            //弹框提示   是否保存数据
            sportAlertDialogUtil.showUploadDialog(this);
        }else{
            //弹框提示  本次运动距离太短
            sportAlertDialogUtil.showNotUploadDialog(this);
        }
    }

    /**
     * 提交数据
     */
    public void updateData(){
        getIntentData.uploadRunningData(UserBean.getUserBean().userId,4,
                "","","",sportCor+"","","","",sportDis+"","","",getDate(sportTime),"","",
                "","","",
                "",locusphoto.toString(),String.valueOf(numTotal));
    }

    private void doFinish() {
        //跑步机停止
        //关闭跑步机
        controller.write(bluDataUtil.startStop("0"));         //停止
        finish();
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Log.e("onKeyDown","------------------------------->");
            if(bluState != 0){
                showDialog();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 这是兼容的 AlertDialog
     */
    private void showDialog() {
      /*
          这里使用了 android.support.v7.app.AlertDialog.Builder
          可以直接在头部写 import android.support.v7.app.AlertDialog
          那么下面就可以写成 AlertDialog.Builder
      */
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("跑步提示");
        builder.setMessage("跑步还在进行中，请结束后退出？");
        builder.setNegativeButton("结束", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(sportDis > 0.1){
                    //弹框提示   是否保存数据
                    sportAlertDialogUtil.showUploadDialog(FavouritMapActivity.this);
                }else{
                    //弹框提示  本次运动距离太短
                    sportAlertDialogUtil.showNotUploadDialog(FavouritMapActivity.this);
                }

            }
        });
        builder.setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }

}
